package com.guodi.map.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.utils.HttpRequester;
import com.guodi.common.utils.HttpRespons;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.log.publisher.UsualLogPublisher;
import com.guodi.core.tool.api.R;
import com.guodi.core.tool.utils.ObjectUtil;
import com.guodi.map.entity.MapDatabaseSource;
import com.guodi.map.service.IMapDatabaseSourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.function.Consumer;


/**
* 数据源 前端控制器
* @作者： 陈宏成
* @日期： 2022-01-18
*/
@Slf4j
@Validated
@RestController
@RequestMapping("/MapDatabaseSource")
@Api(value = "API - MapDatabaseSourceController", tags = "数据源")
public class MapDatabaseSourceController extends BaseController {

    @Resource
    private IMapDatabaseSourceService iMapDatabaseSourceService;

    // GDDataTables 密码加密秘钥
    private String key = "GDSOEDESKEY";

    /**
    * 新增 数据源 记录
    * @作者： 陈宏成
    * @日期： 2022-01-18
    */
    @PostMapping("/save")
    @ApiOperation(value = "新增 数据源 记录")
    public R<MapDatabaseSource> save(@Validated MapDatabaseSource mapDatabaseSource){
        // 新增
        boolean save = this.iMapDatabaseSourceService.save(mapDatabaseSource);
        if (save){
            return R.data(this.iMapDatabaseSourceService.getById(mapDatabaseSource.getId()));
        }else{
            return R.fail("新增失败");
        }
    }

    /**
    * 修改 数据源 记录
    * @作者： 陈宏成
    * @日期： 2022-01-18
    */
    @PostMapping("/update")
    @ApiOperation(value = "修改 数据源 记录")
    public R<MapDatabaseSource> update(@Validated MapDatabaseSource mapDatabaseSource){
        // 修改
        boolean update = this.iMapDatabaseSourceService.updateById(mapDatabaseSource );
        if (update){
            return R.data(this.iMapDatabaseSourceService.getById(mapDatabaseSource.getId()));
        }else{
            return R.fail("修改失败");
        }
    }

    /**
    * 删除 数据源 记录
    * @作者： 陈宏成
    * @日期： 2022-01-18
    */
    @PostMapping("/delete")
    @ApiOperation(value = "删除 数据源 记录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "主键id，如果多个，英文逗号隔开", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<List<MapDatabaseSource>> delete(@Validated @NotBlank(message = "请选择记录再进行删除！") String ids){
        List<String> idList = Arrays.asList(ids.trim().split(","));
        List<MapDatabaseSource> mapDatabaseSources = this.iMapDatabaseSourceService.listByIds(idList);
        boolean remove = this.iMapDatabaseSourceService.removeByIds(idList);
        if (remove){
            return R.data(mapDatabaseSources);
        }else{
            return R.fail("删除失败");
        }
    }

    /**
    * 获取 数据源 列表
    * @作者： 陈宏成
    * @日期： 2022-01-18
    */
    @PostMapping("/page")
    @ApiOperation(value = "获取 数据源 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "size", value = "页面大小，默认10", dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "current", value = "当前页码，默认1",  dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "keyword", value = "关键字，对数据库实例、ip生效",  dataType = "string", paramType = "query"),
    })
    public R<Page<MapDatabaseSource>> page(@ApiIgnore Page page, String keyword){
        LambdaQueryWrapper<MapDatabaseSource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(MapDatabaseSource::getCreateTime);
        if (StringUtils.isNotBlank(keyword)){
            queryWrapper.and(new Consumer<LambdaQueryWrapper<MapDatabaseSource>>() {
                @Override
                public void accept(LambdaQueryWrapper<MapDatabaseSource> mapDatabaseSourceLambdaQueryWrapper) {
                    mapDatabaseSourceLambdaQueryWrapper.like(MapDatabaseSource::getInstance, keyword);
                    mapDatabaseSourceLambdaQueryWrapper.or();
                    mapDatabaseSourceLambdaQueryWrapper.like(MapDatabaseSource::getIp, keyword);
                }
            });
        }
        Page page1 = this.iMapDatabaseSourceService.page(page,queryWrapper);
        return R.data(page1);
    }

    /**
    * 获取 数据源 详情
    * @作者： 陈宏成
    * @日期： 2022-01-18
    */
    @PostMapping("/detail")
    @ApiOperation(value = "获取详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R<MapDatabaseSource> detail(@Validated @NotBlank(message = "请选择记录再进行查看详情") String id){
        MapDatabaseSource mapDatabaseSource = this.iMapDatabaseSourceService.getById(id);
        return R.data(mapDatabaseSource);
    }

    /**
     * 获取 数据源 详情
     * @author 陈宏成
     * @date 2022-01-18
     */
    @PostMapping("/getDataSource")
    @ApiOperation(value = "获取详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R getDataSource(String name){
        LambdaQueryWrapper<MapDatabaseSource> wrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotEmpty(name)){
            wrapper.eq(MapDatabaseSource::getSourceName,name);
        }
        List<MapDatabaseSource> list = this.iMapDatabaseSourceService.list(wrapper);
        return R.data(list);
    }

    /**
     * 获取数据源表
     * @作者： 陈宏成
     * @日期： 2022-02-11
     */
    @PostMapping("/listSoeDBTable")
    @ApiOperation(value = "获取数据源表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R<List<JSONObject>> listSoeDBTable(String soeUrl, MapDatabaseSource databaseSource) throws Exception {
        HttpRequester httpRequester = new HttpRequester();
        HashMap<String, String> params = new HashMap<>();
        params.put("f", "pjson");
        params.put("id",databaseSource.getId());
        soeUrl=soeUrl+"?"+"f=pjson&id="+databaseSource.getId();
        if(StringUtils.isNotBlank(databaseSource.getFeatureDatasetName())){
            soeUrl =soeUrl+"&featureDatasetName="+databaseSource.getFeatureDatasetName();
        }
        if(StringUtils.isNotBlank(databaseSource.getSystem())){
            soeUrl=soeUrl+"&system="+databaseSource.getSystem();
        }
        HttpRespons respons = httpRequester.sendGet(soeUrl,  new HashMap<>());
        JSONObject jsonObject = JSON.parseObject(respons.getContent());
        List<JSONObject> result = new LinkedList<>();
        if (ObjectUtil.isNotEmpty(jsonObject)) {
            if (Objects.equals(true, jsonObject.getBoolean("status")) && Objects.nonNull(jsonObject.getJSONObject("data"))
                    && Objects.nonNull(jsonObject.getJSONObject("data").get("items"))
                    && !jsonObject.getJSONObject("data").getJSONArray("items").isEmpty()) {
                // 获取数据集
                JSONArray items = jsonObject.getJSONObject("data").getJSONArray("items");
                for (Object item : items) {
                    JSONObject itemObject = (JSONObject) item;
                    itemObject.put("children", new ArrayList<>());
                    result.add(itemObject);
                }
            } else {
                if (Objects.equals(false, jsonObject.getBoolean("status")) && Objects.nonNull(jsonObject.getString("message"))) {
                    UsualLogPublisher.publishEvent("error", "GDDataTables接口查询", jsonObject.getString("message"));
                }
            }
        }
        return R.data(result);
    }

    /**
    * @描述: 测试数据库是否可以连接
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2022/4/28 14:56
    **/
    @PostMapping("/testDB")
    @ApiOperation(value = "测试数据库是否可以连接")
    public R testDB(MapDatabaseSource databaseSource) throws ClassNotFoundException {
        return R.data(iMapDatabaseSourceService.testDB(databaseSource));
    }
}
